package com.gwtcx.server.handler;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtcx.server.dao.UserDao;
import com.gwtcx.server.dao.UserDaoFirst;
import com.gwtcx.server.domain.User;
import com.gwtcx.server.util.Security;
import com.gwtcx.shared.action.LoginAction;
import com.gwtcx.shared.action.LoginResult;
import com.gwtcx.shared.exception.LoginException;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class LoginHandler implements ActionHandler<LoginAction, LoginResult> {
	@Inject 
	UserDaoFirst userDao;
	
	private final Provider<HttpServletRequest> requestProvider;
	// private final ServletContext servletContext;

	@Inject
	LoginHandler(final ServletContext servletContext, final Provider<HttpServletRequest> requestProvider) {
		this.requestProvider = requestProvider;
	    // this.servletContext = servletContext;
	}

	@Override
	public LoginResult execute(final LoginAction action, final ExecutionContext context) throws ActionException {
	    LoginResult result = null;

	    try {
	    	User user = userDao.retrieveUser(action.getLogin());

	    	if (user != null && isValidLogin(action, user)) {
	    		HttpSession session = requestProvider.get().getSession();
	    		session.setAttribute("login.authenticated", action.getLogin());

	    		result = new LoginResult(session.getId());
	    	}
	    	else {
	    		throw new LoginException("Invalid User name or Password.");
	    	}
	    }
	    catch (Exception e) {
	    	throw new ActionException(e);
	    }

	    return result;
	}

	private Boolean isValidLogin(LoginAction action, User user) {
		String hash = Security.md5(user.getSalt() + action.getPassword());

		return hash.equals(user.getPassword());
	}

	@Override
	public Class<LoginAction> getActionType() {
		return LoginAction.class;
	}

	@Override
	public void undo(LoginAction action, LoginResult result,
		ExecutionContext context) throws ActionException {
	}
}
